package com.css.zfzx.sjcj.modules.hddcMainAFSvyRegion.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.common.spacedata.vo.SpaceDataParamsVo;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcMainAFSvyRegion.repository.HddcMainafsvyregionNativeRepository;
import com.css.zfzx.sjcj.modules.hddcMainAFSvyRegion.repository.HddcMainafsvyregionRepository;
import com.css.zfzx.sjcj.modules.hddcMainAFSvyRegion.repository.entity.HddcMainafsvyregionEntity;
import com.css.zfzx.sjcj.modules.hddcMainAFSvyRegion.service.HddcMainafsvyregionService;
import com.css.zfzx.sjcj.modules.hddcMainAFSvyRegion.viewobjects.HddcMainafsvyregionQueryParams;
import com.css.zfzx.sjcj.modules.hddcMainAFSvyRegion.viewobjects.HddcMainafsvyregionVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author zyb
 * @date 2020-12-14
 */
@Service
public class HddcMainafsvyregionServiceImpl implements HddcMainafsvyregionService {

    @Autowired
    private HddcMainafsvyregionRepository hddcMainafsvyregionRepository;
    @Autowired
    private HddcMainafsvyregionNativeRepository hddcMainafsvyregionNativeRepository;

    @Override
    public JSONObject queryHddcMainafsvyregions(HddcMainafsvyregionQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcMainafsvyregionEntity> hddcMainafsvyregionPage = this.hddcMainafsvyregionNativeRepository.queryHddcMainafsvyregions(queryParams, curPage, pageSize, sort, order);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcMainafsvyregionPage);
        return jsonObject;
    }


    @Override
    public HddcMainafsvyregionEntity getHddcMainafsvyregion(String id) {
        HddcMainafsvyregionEntity hddcMainafsvyregion = this.hddcMainafsvyregionRepository.findById(id).orElse(null);
        return hddcMainafsvyregion;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcMainafsvyregionEntity saveHddcMainafsvyregion(HddcMainafsvyregionEntity hddcMainafsvyregion) {
        String uuid = UUIDGenerator.getUUID();
        hddcMainafsvyregion.setUuid(uuid);
        hddcMainafsvyregion.setCreateUser(PlatformSessionUtils.getUserId());
        hddcMainafsvyregion.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcMainafsvyregion.setIsValid("1");
        hddcMainafsvyregion.setQualityinspectionStatus("0");
        hddcMainafsvyregion.setExtends10("1");
        this.hddcMainafsvyregionRepository.save(hddcMainafsvyregion);
        return hddcMainafsvyregion;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Iterable<HddcMainafsvyregionEntity> saveHddcMainafsvyregionList(List<HddcMainafsvyregionEntity> list) {
        for (HddcMainafsvyregionEntity hddcMainafsvyregion : list) {
            String uuid = UUIDGenerator.getUUID();
            hddcMainafsvyregion.setUuid(uuid);
            hddcMainafsvyregion.setCreateUser(PlatformSessionUtils.getUserId());
            hddcMainafsvyregion.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            hddcMainafsvyregion.setIsValid("1");
            hddcMainafsvyregion.setQualityinspectionStatus("0");
            hddcMainafsvyregion.setExtends10("1");
        }
        return hddcMainafsvyregionNativeRepository.batchSave(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcMainafsvyregionEntity updateHddcMainafsvyregion(HddcMainafsvyregionEntity hddcMainafsvyregion) {
        HddcMainafsvyregionEntity entity = hddcMainafsvyregionRepository.findById(hddcMainafsvyregion.getUuid()).get();
        UpdateUtil.copyNullProperties(entity,hddcMainafsvyregion);
        hddcMainafsvyregion.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcMainafsvyregion.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcMainafsvyregionRepository.save(hddcMainafsvyregion);
        return hddcMainafsvyregion;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcMainafsvyregions(List<String> ids) {
        List<HddcMainafsvyregionEntity> hddcMainafsvyregionList = this.hddcMainafsvyregionRepository.findAllById(ids);
        if (!PlatformObjectUtils.isEmpty(hddcMainafsvyregionList) && hddcMainafsvyregionList.size() > 0) {
            for (HddcMainafsvyregionEntity hddcMainafsvyregion : hddcMainafsvyregionList) {
                hddcMainafsvyregion.setIsValid("0");
                hddcMainafsvyregion.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcMainafsvyregion.setUpdateTime(new Date());
                this.hddcMainafsvyregionRepository.save(hddcMainafsvyregion);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public void exportFile(HddcMainafsvyregionQueryParams queryParams, HttpServletResponse response) {
        List<HddcMainafsvyregionEntity> yhDisasterEntities = hddcMainafsvyregionNativeRepository.exportYhDisasters(queryParams);
        List<HddcMainafsvyregionVO> list = new ArrayList<>();
        for (HddcMainafsvyregionEntity entity : yhDisasterEntities) {
            HddcMainafsvyregionVO yhDisasterVO = new HddcMainafsvyregionVO();
            BeanUtils.copyProperties(entity, yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list, "主要活动断层制图区-面", "主要活动断层制图区-面", HddcMainafsvyregionVO.class, "主要活动断层制图区-面.xls", response);
    }


    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcMainafsvyregionVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcMainafsvyregionVO.class, params);
            List<HddcMainafsvyregionVO> list = result.getList();
            // Excel条数据
            //int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size()));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcMainafsvyregionVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcMainafsvyregionVO yhDisasterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }

    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList(List<HddcMainafsvyregionVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcMainafsvyregionEntity yhDisasterEntity = new HddcMainafsvyregionEntity();
            HddcMainafsvyregionVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcMainafsvyregion(yhDisasterEntity);
        }
    }

    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcMainafsvyregionEntity> hddcMainafsvyregionList = this.hddcMainafsvyregionRepository.queryHddcMainafsvyregionsByProjectId(projectIds);
        if (!PlatformObjectUtils.isEmpty(hddcMainafsvyregionList) && hddcMainafsvyregionList.size() > 0) {
            for (HddcMainafsvyregionEntity hddcMainafsvyregion : hddcMainafsvyregionList) {
                hddcMainafsvyregion.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcMainafsvyregion.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcMainafsvyregion.setIsValid("0");
                this.hddcMainafsvyregionRepository.save(hddcMainafsvyregion);
            }
        }
    }

    @Override
    public void deleteByTaskId(List<String> taskIds) {
        List<HddcMainafsvyregionEntity> hddcMainafsvyregionList = this.hddcMainafsvyregionRepository.queryHddcMainafsvyregionsByTaskId(taskIds);
        if (!PlatformObjectUtils.isEmpty(hddcMainafsvyregionList) && hddcMainafsvyregionList.size() > 0) {
            for (HddcMainafsvyregionEntity hddcMainafsvyregion : hddcMainafsvyregionList) {
                hddcMainafsvyregion.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcMainafsvyregion.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcMainafsvyregion.setIsValid("0");
                this.hddcMainafsvyregionRepository.save(hddcMainafsvyregion);
            }
        }
    }

    @Override
    public String judegeParams(String[] datas) {
        String str = "";
        Set<String> set = new HashSet<String>(Arrays.asList(datas));
        if (!set.contains("ID")) {
            str += "ID,";
        }
        if (!set.contains("TargetRegionID")) {
            str += "TargetRegionID,";
        }
        if (!set.contains("ProjectName")) {
            str += "ProjectName,";
        }
        if (!set.contains("MappingArea")) {
            str += "MappingArea,";
        }
        if (!set.contains("StudiedFaultCount")) {
            str += "StudiedFaultCount,";
        }
        if (!set.contains("AFaultCount")) {
            str += "AFaultCount,";
        }
        if (!set.contains("RSProcess")) {
            str += "RSProcess,";
        }
        if (!set.contains("FieldSvyPtCount")) {
            str += "FieldSvyPtCount,";
        }
        if (!set.contains("TrenchCount")) {
            str += "TrenchCount,";
        }
        if (!set.contains("TrenchVolume")) {
            str += "TrenchVolume,";
        }
        if (!set.contains("DrillCount")) {
            str += "DrillCount,";
        }
        if (!set.contains("DrillLength")) {
            str += "DrillLength,";
        }
        if (!set.contains("GPhWellCount")) {
            str += "GPhWellCount,";
        }
        if (!set.contains("CollectedSampleCount")) {
            str += "CollectedSampleCount,";
        }
        if (!set.contains("SampleCount")) {
            str += "SampleCount,";
        }
        if (!set.contains("DatingSampleCount")) {
            str += "DatingSampleCount,";
        }
        if (!set.contains("GeomorphySvyProjectCount")) {
            str += "GeomorphySvyProjectCount,";
        }
        if (!set.contains("SeismicProjectCount")) {
            str += "SeismicProjectCount,";
        }
        if (!set.contains("CrustalDfmProjectCount")) {
            str += "CrustalDfmProjectCount,";
        }
        if (!set.contains("GeophysicalSvyProjectCount")) {
            str += "GeophysicalSvyProjectCount,";
        }
        if (!set.contains("GeochemicalProjectCount")) {
            str += "GeochemicalProjectCount,";
        }
        if (!set.contains("IsVolcanic")) {
            str += "IsVolcanic,";
        }
        if (!set.contains("SRA")) {
            str += "SRA,";
        }
        if (!set.contains("SDA")) {
            str += "SDA,";
        }
        if (!set.contains("IsNumSimulation")) {
            str += "IsNumSimulation,";
        }
        if (!set.contains("Description")) {
            str += "Description,";
        }
        if (!set.contains("ShowCode")) {
            str += "ShowCode,";
        }
        if (!set.contains("CommentInfo")) {
            str += "CommentInfo,";
        }
        return str;
    }

    @Override
    public void saveHddcMainafsvyregionFromShpFiles(List<List<Object>> list, String provinceName, String cityName, String areaName, String savefilename) {
        if (list != null && list.size() > 0) {
            List<HddcMainafsvyregionEntity> datas = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                List<Object> obs = list.get(i);
                HddcMainafsvyregionEntity data = new HddcMainafsvyregionEntity();
                data.setArea(areaName);
                data.setProvince(provinceName);
                data.setCity(cityName);
                data.setExtends8(savefilename);
                data.setId(obs.get(1).toString());
                data.setTargetregionid(obs.get(2).toString());
                data.setProjectname(obs.get(3).toString());
                data.setMappingarea(Integer.valueOf(obs.get(4).toString()));
                data.setStudiedfaultcount(Integer.valueOf(obs.get(5).toString()));
                data.setAfaultcount(Integer.valueOf(obs.get(6).toString()));
                data.setRsprocess(Integer.valueOf(obs.get(7).toString()));
                data.setFieldsvyptcount(Integer.valueOf(obs.get(8).toString()));
                data.setTrenchcount(Integer.valueOf(obs.get(9).toString()));
                data.setTrenchvolume(Double.valueOf(obs.get(10).toString()));
                data.setDrillcount(Integer.valueOf(obs.get(11).toString()));
                data.setDrilllength(Integer.valueOf(obs.get(12).toString()));
                data.setGphwellcount(Integer.valueOf(obs.get(13).toString()));
                data.setCollectedsamplecount(Integer.valueOf(obs.get(14).toString()));
                data.setSamplecount(Integer.valueOf(obs.get(15).toString()));
                data.setDatingsamplecount(Integer.valueOf(obs.get(16).toString()));
                data.setGeomorphysvyprojectcount(Integer.valueOf(obs.get(17).toString()));
                data.setSeismicprojectcount(Integer.valueOf(obs.get(18).toString()));
                data.setCrustaldfmprojectcount(Integer.valueOf(obs.get(19).toString()));
                data.setGeophysicalsvyprojectcount(Integer.valueOf(obs.get(20).toString()));
                data.setGeochemicalprojectcount(Integer.valueOf(obs.get(21).toString()));
                data.setIsvolcanic(Integer.valueOf(obs.get(22).toString()));
                data.setSra(Integer.valueOf(obs.get(23).toString()));
                data.setSda(Integer.valueOf(obs.get(24).toString()));
                data.setIsnumsimulation(Integer.valueOf(obs.get(25).toString()));
                data.setDescription(obs.get(26).toString());
                data.setShowcode(obs.get(27).toString());
                data.setCommentInfo(obs.get(28).toString());
                data.setExtends16("CGCS2000");
                String pstr = obs.get(0).toString();
                /*String[] ss1 = pstr.split("\\(");
                if (ss1.length == 2) {
                    String[] ss2 = ss1[1].split("\\)");
                    if (ss2.length <= 2) {
                        String spacedata = ss2[0].replace(",", ";").replace(" ", ",");
                        data.setExtends5(spacedata);
                    }
                }*/
                pstr = pstr.replace(")), ((", "#");
                pstr = pstr.replace("), (", "#");
                String[] ss1=pstr.split("\\(");
                if(ss1.length>=2){
                    String[] ss2=ss1[ss1.length-1].split("\\)");
                    if(ss2.length<=2){
                        String spacedata=ss2[0].replace(",",";").replace("; ",";").replace(" ",",");
                        data.setExtends5(spacedata);
                    }
                }
                datas.add(data);
                /*for(int j=0;j<obs.size();j++){
                    Object value=obs.
                }*/
            }
            deleteByCreateUser(provinceName,cityName,areaName);

            saveHddcMainafsvyregionList(datas);
        }
    }

    @Override
    public List<HddcMainafsvyregionEntity> findAll() {
        List<HddcMainafsvyregionEntity> list = this.hddcMainafsvyregionRepository.findAll();
        return list;
    }


    public void deleteByCreateUser(String provinceName,String cityName,String areaName) {
        String createID = PlatformSessionUtils.getUserId();
        List<HddcMainafsvyregionEntity> hddcMainafsvyregionList = this.hddcMainafsvyregionRepository.queryHddcMainafsvyregionByCreateuser(createID,provinceName,cityName,areaName);
        if (!PlatformObjectUtils.isEmpty(hddcMainafsvyregionList) && hddcMainafsvyregionList.size() > 0) {
            hddcMainafsvyregionRepository.deleteAll(hddcMainafsvyregionList);
        }
    }

    @Override
    @Transactional
    public void deleteFileData(SpaceDataParamsVo paramsVo) {
        String provinceName=paramsVo.getProvinceName();
        String cityName=paramsVo.getCityName();
        String areaName=paramsVo.getAreaName();
        String savefilename=paramsVo.getSavefilename();
        hddcMainafsvyregionRepository.deleteFileData(provinceName,cityName,areaName,savefilename);
    }

}
